//
//  DestinationViewController.m
//  WhereToTravel
//
//  Created by dlios on 15/10/12.
//  Copyright © 2015年 zhoushengmin. All rights reserved.
//

#import "DestinationViewController.h"
#import "DestinationCollectionViewCell.h"
#import "OthetDestinationViewCell.h"
#import "DestinationModel.h"
#import "CountryViewController.h"
#import "HeadView.h"
#import "FootView.h"
#import "CityViewController.h"
#import "SeekViewController.h"

@interface DestinationViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *hotCollect;
@property (nonatomic, strong) NSMutableArray *hotArr;
@property (nonatomic, assign) NSInteger clickTag;
@property (nonatomic, strong) UILabel *titleLabel;

@end

@implementation DestinationViewController

// 视图的出现将tabbar显示
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(night) name:@"night" object:nil];
    }
    return self;
}
- (void)creatData {
    [ZSMAFNetWork geturl:@"http://open.qyer.com/qyer/footprint/continent_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=38.88268760865181&lon=121.5397062723905&page=1&track_app_channel=App%2520Store&track_app_version=6.5.5&track_device_info=iPhone7%2C2&track_deviceid=5B302CA5-E537-4B10-955D-520F4C91BAFE&track_os=ios%25208.1.2&v=1" body:nil result:ZSMJSON headerFile:nil success:^(id result) {
        self.hotArr = [NSMutableArray array];
        NSArray *countryArr = result[@"data"];
        for (NSDictionary *dic in countryArr) {
            
            DestinationModel *continent = [[DestinationModel alloc]initWithDic:dic];
            //hotArr放各大洲
            [self.hotArr addObject:continent];
        }
        [self.hotCollect reloadData];
        [self.hotCollect.header endRefreshing];
        self.hud.hidden = YES;
    } failure:^(NSError *error) {
        NSLog(@"error=%@",error);
    }];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatData];
    // Do any additional setup after loading the view.
    [self creatHotCollect];
    self.clickTag = 1000;
    
    // 设置navigationBar颜色
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:87/255.0 green:217/255.0 blue:200/255.0 alpha:1];
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.text = @"目的地";
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    self.navigationItem.titleView = self.titleLabel;

    // 搜索
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"搜索"] style:UIBarButtonItemStylePlain target:self action:@selector(rightButton:)];
}
// 搜索点击方法
- (void)rightButton:(UIBarButtonItem *)barButtonItem {
    SeekViewController *seekVC = [[SeekViewController alloc] init];
    [self.navigationController pushViewController:seekVC animated:YES];
}

- (void)creatHotCollect {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    //设置每行间距
    flowLayout.minimumLineSpacing = 10;

    self.hotCollect = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 565) collectionViewLayout:flowLayout];
    // 注册cell
    [self.hotCollect registerClass:[DestinationCollectionViewCell class] forCellWithReuseIdentifier:@"hotCell"];
    [self.hotCollect registerClass:[OthetDestinationViewCell class] forCellWithReuseIdentifier:@"otherCell"];
    // 签代理
    self.hotCollect.delegate = self;
    self.hotCollect.dataSource = self;
    self.hotCollect.backgroundColor = [UIColor colorWithWhite:0.939 alpha:1.000];
    [self.view addSubview:self.hotCollect];




    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
     [self.hud hide:YES afterDelay:4];
    [self.hotCollect mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.view);        
    }];

    
    // 注册头视图
    [self.hotCollect registerClass:[HeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headCell"];
    // 注册脚视图
    [self.hotCollect registerClass:[FootView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footCell"];
    
//    [self createMJRefresh];
}

- (void)createMJRefresh {
    // 下拉刷新
    self.hotCollect.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(creatData)];
    [self.hotCollect.header beginRefreshing];
}

// collectionView的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    DestinationModel *continent = self.hotArr[self.clickTag-1000];
    if (section == 0) {
      return continent.hot_country.count;
    }else {
      return continent.country.count;
    }

    
}
// 分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 2;
}

// item的显示
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
     DestinationModel *continent = self.hotArr[self.clickTag-1000];
    if (indexPath.section == 0) {
        DestinationCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hotCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
        DestinationModel *country =  [[DestinationModel alloc]initWithDic:continent.hot_country[indexPath.row]];
        [cell.bottomView sd_setImageWithURL:[NSURL URLWithString:country.photo] placeholderImage:[UIImage imageNamed:@"F"]];
        cell.numberLab.text = [country.count description];
        cell.cityLab.text = country.label;
        cell.countryLab.text = country.cnname;
        cell.englishLab.text = country.enname;
    
        return cell;
        
    }else {
        OthetDestinationViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"otherCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
        DestinationModel *country = [[DestinationModel alloc]initWithDic:continent.country[indexPath.row]];
        cell.topName.text = country.cnname;
        cell.engName.text = country.enname;
        return cell;
    }
    
    
}
//对应头尾视图的显示
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
        DestinationModel *continent = self.hotArr[self.clickTag-1000];
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            // 去重用队列取可用的head;
        
            HeadView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headCell" forIndexPath:indexPath];
            view.backImage.image = [UIImage imageNamed:@"ditu"];
//            imageView上添加button的点击事件,必须打开用户交互
            view.backImage.userInteractionEnabled = YES;
            // 7个button设置tag值
            [view.buttonAsia addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            view.buttonAsia.tag = 1000;
            [view.buttonOceania addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            view.buttonOceania.tag = 1004;
            [view.buttonAntarctica addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            view.buttonAntarctica.tag = 1006;
            [view.buttonEurope addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            view.buttonEurope.tag = 1001;
            [view.buttonAfrika addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            view.buttonAfrika.tag = 1005;
            [view.buttonNorthAmerica addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            view.buttonNorthAmerica.tag = 1002;
            [view.buttonSouthAmerica addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
            view.buttonSouthAmerica.tag = 1003;
           
            view.titleLabel.text = [NSString stringWithFormat:@"  %@热门目的地",continent.cnname];
            
            NSLog(@"%@", view.titleLabel.text);
            
            return view;
        }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
            FootView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footCell" forIndexPath:indexPath];
            view.footLabel.text = [NSString stringWithFormat:@"  %@其他目的地",continent.cnname];
            return view;
        }
    return nil;
    
}
// 设置item的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    //判断分区
    if (indexPath.section == 0) {
       return CGSizeMake(WIDTH * 180, HEIGHT * 260);
    }else {
        return CGSizeMake(WIDTH * 180, HEIGHT * 60);
    }
}
// 设置section头视图的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    //强行让别的分区坐标变为0
    if (section == 0) {
        return CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height*0.5);
    }else {
        return CGSizeMake(0, 0);
    }
    
    
}
// 设置section尾视图的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
     //强行让别的分区坐标变为0
    DestinationModel *continent = self.hotArr[self.clickTag-1000];
    if (section == 0 && continent.country.count != 0) {
        return CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height*0.1);
    }else {
        return CGSizeMake(0, 0);
    }
    
}
// 点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    DestinationModel *continent = self.hotArr[self.clickTag-1000];
    
    if (indexPath.section == 0) {
       DestinationModel *country =  [[DestinationModel alloc]initWithDic:continent.hot_country[indexPath.row]];
        // 判断是城市还是旅行地
        if (country.flag == 1) {
            CountryViewController *cVC = [[CountryViewController alloc]init];
             cVC.countryId = country.uId;
             [self.navigationController pushViewController:cVC animated:YES];
        }else if (country.flag == 2) {
            CityViewController *cityC = [[CityViewController alloc]init];
            cityC.cityId = country.uId;
            [self.navigationController pushViewController:cityC animated:YES];
            
        }
       
    }else {
        DestinationModel *country =  [[DestinationModel alloc]initWithDic:continent.country[indexPath.row]];
        if (country.flag == 1) {
            CountryViewController *cVC = [[CountryViewController alloc]init];
            cVC.countryId = country.uId;
            [self.navigationController pushViewController:cVC animated:YES];
        }else if (country.flag == 2) {
            CityViewController *cityC = [[CityViewController alloc]init];
            cityC.cityId = country.uId;
            [self.navigationController pushViewController:cityC animated:YES];
            
        }
    }
}
//各大洲的点击刷新界面
- (void)click:(UIButton *)button {
    // 获取点击哪一个button
    self.clickTag = button.tag;
    
    [self.hotCollect reloadData];
}

- (void)night {
    if ([SingletonNight shareSingletonNight].isSelete == YES) {
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
        self.titleLabel.textColor = [UIColor blackColor];
        self.hotCollect.backgroundColor = [UIColor blackColor];
    }
    else {
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:87/255.0 green:217/255.0 blue:200/255.0 alpha:1];
        self.titleLabel.textColor = [UIColor whiteColor];
        self.hotCollect.backgroundColor = [UIColor colorWithWhite:0.939 alpha:1.000];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"night" object:nil];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
